<?php
use think\Db;
/*
 *user_id 用戶ID
 *type 類型1關懷任務2培訓任務
 *relation_id 關聯ID
 *workinghours 工時
 *score 積分
 *exp 經驗
 *createtime 創建時間
*增加任務記錄
*/
function addTaskLog($user_id,$type,$relation_id,$workinghours,$score,$exp,$createtime=0)
{
	$createtime = $createtime?$createtime:time();
    Db::startTrans();
    try {
    	$user = db('user')->where(['id'=>$user_id])->find();
    	$task_log_arr = [];
    	$task_log_arr['user_id'] = $user_id;
    	$task_log_arr['type'] = $type;
    	$task_log_arr['relation_id'] = $relation_id;
    	$task_log_arr['workinghours'] = $workinghours;
    	$task_log_arr['score'] = $score;
    	$task_log_arr['exp'] = $exp;
    	$task_log_arr['createtime'] = $createtime;
    	$status = db('task_log')->insertGetId($task_log_arr);
    	if ( !$status ) {
	        Db::rollback();
	        return false;
    	}

		$exp_nex = $user['exp']+$exp;
		db('user')->where(['id'=>$user_id])->setInc('exp',$exp);
		db('user')->where(['id'=>$user_id])->setInc('workinghours',$workinghours);
		$momo = $type=='1'?'完成關懷任務':"完成培訓任務";
		// 加積分
		$status = addPoints($user_id,$score,$momo,$type,$relation_id,$createtime);
		if ( !$status ) {
	        Db::rollback();
	        return false;
		}
		$level_arr = nextlevel($exp_nex);
		$level_arr['updatetime'] = $createtime;
		db('user')->where(['id'=>$user_id])->update($level_arr);
        // 提交事务
        Db::commit();
    } catch (\Exception $e) {
        // 回滚事务
        Db::rollback();
        return false;
    }
    return true;
}

/**
 * 根据經驗获取等级
 * @param int $exp 經驗
 * @return int
 */
function nextlevel($exp = 0)
{
    $lv = db('volunteer_level')->field(['id,level,name,exp_start,exp_end'])->order('id asc')->select();
    $level = $lv[0]['level'];
    $level_name = $lv[0]['name'];
    foreach ($lv as $key => $value) {
        if ($exp >= $value['exp_start']) {
            $level = $value['level'];
            $level_name = $value['name'];
        }
    }
    return ['level'=>$level,'level_name'=>$level_name];
}